package com.cloudcross.ssp.common.mail;

import java.util.Date;
import java.util.Properties;

import javax.mail.BodyPart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import com.adinall.dsp.core.utils.CheckUtils;
import com.cloudcross.ssp.common.utils.PropertiesUtils;

public class Mail {

    public void send(String tos, String ccs, String subject, String content) throws Exception {

        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.host", PropertiesUtils.getProperty("/application.properties", "mail.smtp.host"));
        props.setProperty("mail.smtp.port", "25");
        props.setProperty("mail.smtp.auth", "true");

        Session session = Session.getDefaultInstance(props);
        session.setDebug(false);

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(PropertiesUtils.getProperty("/application.properties", "mail.smtp.fromAddress"),
                PropertiesUtils.getProperty("/application.properties", "mail.smtp.personal"), "UTF-8"));

        String[] arr = tos.split(",");

        for (String to : arr) {
            message.addRecipients(MimeMessage.RecipientType.TO, to);
        }

        if (!CheckUtils.isEmpty(ccs)) {

            arr = ccs.split(",");
            for (String cc : arr) {
                message.addRecipients(MimeMessage.RecipientType.CC, cc);
            }
        }

        message.setSubject(subject, "UTF-8");

        MimeMultipart mmp = new MimeMultipart("mixed");

        if (content != null) {
            mmp.addBodyPart(attachedContent(content));
        }

        message.setContent(mmp);
        message.setSentDate(new Date());
        message.saveChanges();

        // 信息传输
        Transport transport = session.getTransport();

        String username = PropertiesUtils.getProperty("/application.properties", "mail.smtp.username");
        String password = PropertiesUtils.getProperty("/application.properties", "mail.smtp.password");
        transport.connect(username, password);
        transport.sendMessage(message, message.getAllRecipients());

        transport.close();
    }

    private BodyPart attachedContent(String text) throws Exception {

        BodyPart part = new MimeBodyPart();
        part.setText(text);
        return part;
    }
}